package com.compass.doctor.ui.patient

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnChatMenuClick
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.callback.OnGiveMessageCallBack
import com.compass.doctor.callback.UnderwayCallback
import com.compass.doctor.databinding.ActivityDoctorChatBinding
import com.compass.doctor.dialog.FinishInquiryDialog
import com.compass.doctor.dialog.PresentedNumberDialog
import com.compass.doctor.dialog.UsefulExpressionsDialog
import com.compass.doctor.ui.chat.util.CustomUIConfig
import com.compass.doctor.ui.home.SpecialColumnActivity
import com.compass.doctor.ui.home.viewmodel.InquiryOrderViewModel
import com.compass.doctor.ui.mine.UsefulExpressionsActivity
import com.compass.doctor.ui.patient.fragment.MyChatFragment
import com.compass.doctor.ui.patient.viewmodel.PatientViewModel
import com.compass.doctor.ui.prescription.PrescribeForWesternMedicineActivity
import com.compass.doctor.ui.setting.ReportActivity
import com.compass.framework.R
import com.compass.framework.constant.CHAT_INFO
import com.compass.framework.constant.CLINICAL_RECEPTION
import com.compass.framework.constant.KEY_PATIENT_ID
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.visible
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.InquiryCase
import com.compass.framework.model.UnderwayOrder
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.getStringFromResource
import com.netease.yunxin.kit.chatkit.ui.view.input.ActionConstants
import com.netease.yunxin.kit.chatkit.ui.view.useful.IExpressionButtonClickListener
import com.netease.yunxin.kit.corekit.im.model.UserInfo
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant

/**
 * Description： 医护/护师对患者聊天界面
 * Date:2024/5/12 16:34
 */
class PractitionerToPatientChatActivity : BaseVBActivity<ActivityDoctorChatBinding>() {

    companion object {
        fun start(context: Context, userInfo: UserInfo, patientId: String) {
            val intent = Intent(context, PractitionerToPatientChatActivity::class.java)
            intent.putExtra(CHAT_INFO, userInfo)
            intent.putExtra(KEY_PATIENT_ID, patientId)
            context.startActivity(intent)
        }
    }

    private val patientViewModel: PatientViewModel by viewModels()
    private val inquiryOrderViewModel: InquiryOrderViewModel by viewModels()


    private lateinit var chatFragment: MyChatFragment//单聊Fragment

    private lateinit var patientId: String//患者ID
    private var orderId: String? = null//问诊单ID
    private lateinit var userInfo: UserInfo//云信信息
    private lateinit var msgSuggestion: String//诊后建议内容
    private var underwayOrder: UnderwayOrder? = null
    private var underwayCallback: UnderwayCallback = object : UnderwayCallback {
        override fun onReceiveMessageCallback() {
            underwayOrder?.let {
                if (it.consultResidueNum > 0) {
                    it.consultResidueNum--
                    CustomUIConfig.setTopTips(it)
                } else {
                    it.consultResidueNum = 0
                    CustomUIConfig.setTopTips(it)
                }
            }
        }
    }

    //输入框上部菜单点击事
    private var onChatBottomClick: OnCustomButtonClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, msgType: String?) {
            msgType?.let {
                chatBottomClick(msgType)
            }
        }
    }

    //常用语菜单点击事件回调
    private var iExpressionButtonClickListener: IExpressionButtonClickListener =
        IExpressionButtonClickListener { _, name ->
//            UsefulExpressionsDialog.Builder(this).show()
        }

    private var onChatMenuClick: OnChatMenuClick = object : OnChatMenuClick {
        override fun onMenuCallBack(action: String) {
            onCustomItemClick(action)
        }
    }

    private var onGiveMessageCallBack: OnGiveMessageCallBack = object : OnGiveMessageCallBack {
        override fun onMessageCallBack(giveNumber: String, giveTime: String) {
            inquiryOrderViewModel.giveMessaging(giveNumber, giveTime, patientId)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        userInfo = intent.serializable(CHAT_INFO)!!
        patientId = intent.serializable(KEY_PATIENT_ID)!!
        mBinding.tvTitleBar.setMiddleText(userInfo.getUserInfoName())

        //获取进行中的问诊单
        showLoading()
        inquiryOrderViewModel.getUnderwayOrder(patientId)

        mBinding.tvTitleBar.getRightLayout().onClick {
            if (UserInfoManager.getUserType() == "1") {
                checkMedicalRecord(0)
            } else {
                finishInquiry()
            }


        }


    }

    /**
     * 结束问诊
     */
    private fun finishInquiry() {
        showLoading()
        //结束问诊直接调用
        inquiryOrderViewModel.finishInterrogation(orderId, null)

//        FinishInquiryDialog.Builder(this, 2, object : OnCustomButtonClick {
//            override fun onButtonCallBack(codeType: Int, msg: String?) {
//                if (!msg.isNullOrEmpty()) {
//                    msgSuggestion = msg
//                    showLoading()
//                    inquiryOrderViewModel.finishInterrogation(orderId, msg)
//                } else {
//                    showToast("请输入诊后建议")
//                }
//            }
//        }).show()
    }

    private fun setRightView(status: Int) {
        mBinding.tvTitleBar.getRightTextView().gone()
        orderId?.let {
            if (status == 2) {
                mBinding.tvTitleBar.getRightTextView().visible()
                mBinding.tvTitleBar.setRightText("结束问诊")
            }
        } ?: kotlin.run {
            mBinding.tvTitleBar.getRightTextView().gone()
        }
    }

    //是否是赠送条数
    private var isGiveMessaging: Boolean = false
    override fun initData() {

        inquiryOrderViewModel.finishLiveData.observe(this) {
            dismissLoading()
            if (it) {
                LiveDataBus.get().with(CLINICAL_RECEPTION)
                    .postValue(CLINICAL_RECEPTION)
                showToast("结束成功")
                finish()
            }
        }
        inquiryOrderViewModel.giveLiveData.observe(this) {
            if (it) {
                isGiveMessaging = true
                showToast("赠送成功")
                inquiryOrderViewModel.getUnderwayOrder(patientId)
            }
        }
        inquiryOrderViewModel.wayOrderLiveData.observe(this) {
            dismissLoading()
            underwayOrder = it
            underwayOrder?.let { underwayOrder ->
                if (!isGiveMessaging) {
                    underwayOrder.orderId?.let { id ->
                        orderId = id

                        setImMenu(true, underwayOrder)
                    } ?: kotlin.run {
                        setImMenu(false, underwayOrder)
                    }
                } else {
                    //刷新条数
                    CustomUIConfig.setTopTips(underwayOrder)
                }

                setRightView(underwayOrder.status)
            } ?: kotlin.run {
                if (!isGiveMessaging) {
                    setImMenu(false, null)
                }
            }


        }
        patientViewModel.inquiryCaseLiveData.observe(this) { case ->
            dismissLoading()
            case?.let {
                if (case.status == 0) {
                    //没有按钮且按钮不是添加病历按钮
                    when (comeType) {
                        0, 1, 2, 3 -> {
                            onAddCaseDialog(it)
                        }

                        4 -> {
                            AddInquiryCaseHistory.start(
                                this,
                                patientId,
                                case.diseaseDescription,
                                null,
                                orderId, 1
                            )

                        }
                    }
                } else {
                    comeTypeOperate(it)
                }
            }
        }
    }

    /**
     *
     */
    private fun onAddCaseDialog(case: InquiryCase) {
        CommonMessageDialog.Builder(this)
            .setTitle(getStringFromResource(R.string.dialog_tips_title))
            .setMessage("请先添加患者病历")
            .setConfirm(getStringFromResource(R.string.default_confirm))

            .setCancel(getString(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                AddInquiryCaseHistory.start(
                    this,
                    patientId,
                    case.diseaseDescription,
                    null,
                    orderId, 1
                )
                it?.dismiss()
            }.create().show()
    }

    /**
     *
     * @param isInquiry 是否有正在进行中的问诊
     */
    private fun setImMenu(isInquiry: Boolean, underwayOrder: UnderwayOrder?) {


        CustomUIConfig.initChatMoreMenu(
            false,
            isInquiry,
            underwayOrder?.ifReturnVisit,
            onChatMenuClick
        )


        CustomUIConfig.initChatBottomAndTopLayout(
            true, isInquiry,
            onChatBottomClick,
            iExpressionButtonClickListener, underwayOrder
        )
        initFragment()


    }


    /**
     * 菜单按钮点击 方法 待定是否写在这里
     */
    private fun onCustomItemClick(action: String) {
        when (action) {
            //举报消息
            ActionConstants.CUSTOM_ACTION_TYPE_REPORT -> {
                //举报
                ReportActivity.start(this)

            }

            ActionConstants.CUSTOM_ACTION_TYPE_COUPE -> {
                //科普
                SpecialColumnActivity.start(this, 2, patientId)

            }

            ActionConstants.CUSTOM_ACTION_TYPE_PRESCRIBING -> {
                checkMedicalRecord(1)

            }

            ActionConstants.CHAT_HOSPITALIZATION_CERTIFICATE -> {
                checkMedicalRecord(2)

            }

            ActionConstants.CUSTOM_ACTION_TYPE_INSPECT -> {
                checkMedicalRecord(3)

            }

            ActionConstants.CHAT_CASE_HISTORY -> {
                checkMedicalRecord(4)


            }
        }
    }

    private fun initFragment() {
        //set fragment
        chatFragment = MyChatFragment()
        val bundle = Bundle()
        bundle.putString(KEY_PATIENT_ID, patientId)
        bundle.putSerializable(RouterConstant.CHAT_KRY, userInfo)
        chatFragment.arguments = bundle
        chatFragment.setUnderwayCallback(underwayCallback)

        val fragmentManager = supportFragmentManager
        fragmentManager.beginTransaction().add(com.compass.doctor.R.id.container, chatFragment)
            .commitAllowingStateLoss()

    }

    private fun chatBottomClick(msgType: String) {
        when (msgType) {
            ActionConstants.RAPID_PRESCRIBING -> {
                checkMedicalRecord(1)

            }

            ActionConstants.USEFUL_EXPRESSIONS -> {
                //常用语
//                CustomUIConfig.showUseful()
                UsefulExpressionsActivity.start(this)
            }

            ActionConstants.PRESENTED_NUMBER -> {
                PresentedNumberDialog.Builder(this, onGiveMessageCallBack).show()
            }

        }
    }


    private var comeType: Int? = null

    /**
     * 检查是否开过病历
     * @param comeType 0结束问诊 1处方 2开住院证 3开检验检查
     */
    private fun checkMedicalRecord(comeType: Int) {
        this.comeType = comeType
        showLoading()
        patientViewModel.getInquiryCaseHistory(patientId)
    }


    /**
     * 不同comeType的操作
     */
    private fun comeTypeOperate(case: InquiryCase) {
        when (comeType) {
            0 -> {
                //结束问诊
                finishInquiry()
            }

            1 -> {
                UserInfoManager.getUserInfo()?.let {
                    if (it.prescriptionAllow == 1) {
                        //快速开药/处方开药
                        PrescribeForWesternMedicineActivity.start(
                            this,
                            userInfo,
                            patientId,
                            case.presentDiseaseContent
                        )
                    } else {
                        showToast("您还没有开具处方的权限")
                    }
                }
            }

            2 -> {
                //住院证
                UserInfoManager.getUserInfo()?.let {
                    if (it.hospitalizedAllow == 1) {
                        orderId?.let { id ->
                            HospitalizationCertificateActivity.start(
                                this,
                                patientId,
                                userInfo.account,
                                id
                            )
                        }
//                        HospitalizationCertificateActivity.start(this, patientId, userInfo.account,id)
                    } else {
                        showToast("您还没有开具住院证的权限")
                    }
                }

            }

            3 -> {
                //检验检查
                UserInfoManager.getUserInfo()?.let {
                    if (it.examinationAllow == 1) {
                        //检验检查
                        ExaminationActivity.start(this, patientId, userInfo.account)
                    } else {
                        showToast("您还没有开检验检查的权限")
                    }
                }

            }

            4 -> {
                AddInquiryCaseHistory.start(this, patientId, null, case.id, null, 0)
            }
        }

    }
}
